﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using MyERP.Models;

namespace MyERP.WebApi
{
    [Route("api/[controller]/[Action]")]
    [ApiController]
    [Authorize(Roles = "admin,q2")]
    public class SupplierController : ControllerBase
    {
        private MyDbContext db;
        public SupplierController(MyDbContext myDbContext)
        {
            db = myDbContext;
        }
        /// <summary>
        /// 返回供应商名字列表
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public List<string> AllName()
        {
            return db.Supplier.Select(s => s.Name).ToList();
        }
        /// <summary>
        /// 添加供应商
        /// </summary>
        /// <param name="sData"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ActionResult> Add([FromBody] Supplier sData)
        {
            //判断供应商是否存在，如果不存在再继续添加供应商
            Supplier? s = db.Supplier.FirstOrDefault(a => a.Name == sData.Name);
            if (s == null)
            {
                db.Supplier.Add(sData);
                await db.SaveChangesAsync();
                return Ok();
            }
            return NotFound();
        }
    }
}
